import re

from flask import session
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, ValidationError
from wtforms.validators import DataRequired, Length, EqualTo

from app.models import User
from app.uilts import pwd_md5


class UserUpdatePwd(FlaskForm):
    username = StringField(validators=[DataRequired(message='必须填写账号'), Length(5,10, message='用户请输入5-10位')])
    tel = StringField(validators=[DataRequired(message='必填字段'), Length(11,11, message='请输入11位手机号')])
    old_password = StringField(validators=[DataRequired(message='必填字段'), Length(6, 12, message='密码长度为6-12位')])
    password = StringField(validators=[DataRequired(message='必填字段'), Length(6, 12, message='密码长度为6-12位')])
    new_password = StringField(EqualTo('password', message='两次密码不一致'))

    def validate_username(self, name):
        user = User.query.filter(User.username == name.data).first()
        if user:
            raise ValidationError('用户名以存在')

    def validate_old_password(self, field):
        user = session.get('user')
        old_password = pwd_md5(field.data)
        if user.password != old_password:
            raise ValidationError('密码错误')
